document.addEventListener('DOMContentLoaded', () => {
    refreshFileList();
});

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function refreshFileList() {
    fetch('/list-files')
    .then(response => response.json())
    .then(data => {
        const fileListElement = document.getElementById('fileList');
        fileListElement.innerHTML = '';

        data.forEach(file => {
            const li = document.createElement('li');
            const link = document.createElement('a');
            link.href = `/download/${encodeURIComponent(file.name)}`;
            link.textContent = file.name;

            const sizeSpan = document.createElement('span');
            sizeSpan.textContent = ` (${formatFileSize(file.size)})`;

            li.appendChild(link);
            li.appendChild(sizeSpan);
            fileListElement.appendChild(li);
        });
    })
    .catch(error => {
        console.error('获取文件列表时出错:', error);
    });
}